package comunication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

import model.Game;

/**
 * Class of SocketServer, which provides service, such as creating an object of ClientWorker class for each client.
 * @author Agnieszka Rucinska
 *  
 */

public class SocketServer extends Thread{
	private ServerSocket server = null;
	private BufferedReader in = null;
	private PrintWriter out = null;
	private Socket client = null;
	private Game game = null;
	private int playersNr; 
	
	
	public SocketServer(int port, int playersNr, Game game){
		try{
			this.game = game;
			this.playersNr = playersNr;
			server = new ServerSocket(port);
			System.out.println("Server on port " + server.getLocalPort()
					+ " started Jupi!.");
		}
		catch (IOException e){
			JOptionPane.showMessageDialog(null, "Could not listen on port " + port ,
					"Error", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		catch(IllegalArgumentException e){
			JOptionPane.showMessageDialog(null, "You cannot create the game\non this port" ,
					"Error", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
	}

	/**
	 * method loops on the server, accept call waiting for client connections and creates an instance of the Player class
	 *  for each client connection it accepts.
	 */
	public void run(){
		int counter = 0;
		while(counter<playersNr){
			try{
				client = server.accept();
				System.out.println("Client " + client.getInetAddress()+"  "+ client.getPort() + " accepted on port.");
				in = new BufferedReader(new InputStreamReader(client.getInputStream()));
				out = new PrintWriter(client.getOutputStream(),true);
				String line = in.readLine();
				if(line.startsWith("Name_")){
					String name = line.substring(5);
					if(game.isNameFree(name)){
						out.println("Accepted_");
						PlayerCommunicator plCom = new PlayerCommunicator(client, game, counter+1);
						game.sitPlayer(plCom,name);
						counter++;
					}
					else{
						out.println("BadName_");
					}
				}
			} 
			catch (IOException e){
				System.out.println("Accept failed:" + client.getInetAddress());
				System.exit(-1);
			}
		}
		try{
			sleep(2000);
		} 
		catch (InterruptedException e){
			System.out.println("I cannot sleep");
		}
		game.startGame();
	}
		
	
	protected void finalize(){
		try{
			in.close();
			out.close();
			server.close();
		}
		catch (IOException e){
			System.out.println("Could not close.");
			System.exit(-1);
		}
	}
}
